package com.yuke.cloud.service.wmc.controller.frontend;
/*
 * <p>Company: Copyright (c) 2018. yuke All Rights Reserved. </br> </p>
 * <p>Title：yuke-mall </br> </p>
 * <p>com.yuke.cloud.service.omc.controller.frontend Description TODO </br> </p>
 * @Author wg
 * @Date   2020/5/2 17:02
 */

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yuke.cloud.common.util.DateUtil;
import com.yuke.cloud.common.util.excel.ZipUtil;
import com.yuke.cloud.common.util.wrapper.Wrapper;
import com.yuke.cloud.service.wmc.dto.*;
import com.yuke.cloud.service.wmc.entity.WmsStorage;
import com.yuke.cloud.service.wmc.service.WmsPurchaseReturnOrderService;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static com.yuke.cloud.common.util.excel.ExcelOutUtil.getMergePaperPath;
import static com.yuke.cloud.common.util.excel.ExcelOutUtil.helpdown;
import static com.yuke.cloud.common.util.excel.ZipUtil.fileToZip;

/**
 * 仓库中心
 * 导出报表
 *
 * @return
 */

@RestController
@RequestMapping("/storageExcel")
public class WmsStockOutExport {

    @Resource
    private WmsStorageController wmsStorageController;

    @Resource
    private WmsPurchaseReturnOrderService  wmsPurchaseReturnOrderService;

    //出库统计
    @RequestMapping("/outCount")
    @ResponseBody
    public void export(
            @ApiParam(name = "page", value = "分页值", defaultValue = "1") @RequestParam(defaultValue = "1") Integer page,
            @ApiParam(name = "size", value = "每分页返回的记录数", defaultValue = "1000") @RequestParam(defaultValue = "1000") Integer size,
            @ApiParam(name = "warehouseId", value = "仓库id", defaultValue = "0") @RequestParam(required = false) Long warehouseId,
            @ApiParam(name = "specId", value = "产品规格id", defaultValue = "0") @RequestParam(required = false) Long specId,
            @ApiParam(name = "outType", value = "出库类型", defaultValue = "0") @RequestParam(required = false) Byte outType,
            @ApiParam(name = "beginTime", value = "开始时间", defaultValue = "0") @RequestParam(required = false) Long beginTime,
            @ApiParam(name = "endTime", value = "结束时间", defaultValue = "0") @RequestParam(required = false) Long endTime,
            @ApiParam(name = "purchaseReturnId", value = "purchaseReturnId", defaultValue = "0") @RequestParam(required = false)  Long purchaseReturnId,
            @ApiParam(name = "orderId", value = "orderId", defaultValue = "0") @RequestParam(required = false)  Long orderId,
            HttpServletRequest request,HttpServletResponse response
    ) throws Exception {

        //excel标题
        String[] title ={ "序号", "商品名称", "商品分类", "出库类型", "出库数量", "出库时间","订单号","进货退货单号"};

        String [] properties = new String[]{"index", "specName", "categoryName", "outType", "outNumber", "outboundTime","orderId","purchaseReturnId"};

        //excel文件名
        String fileName = "出库统计" + System.currentTimeMillis() + ".xls";

        //sheet名
        String sheetName = "出库统计表";

        //zip文件名
        String zipName = "出库统计表";

        //zip路径名
        String zipNameString = zipName+".zip";

        //不同系统文件夹的生成
        String mergePaperPath = getMergePaperPath(new Date());

        ZipUtil zipUtil = new ZipUtil();

        boolean flag =true;
        //存入地址
        List<File> tempPath = new ArrayList<>();

        while(flag){

            List<Map> map = new ArrayList<>();

            int index = 1;

            Wrapper<PageInfo<WmsStockOutDto>> search = wmsStorageController.search(page, size, warehouseId, specId, outType, beginTime, endTime,purchaseReturnId,orderId);

            PageInfo<WmsStockOutDto> result = search.getResult();

            List<WmsStockOutDto> list = result.getList();
            for ( WmsStockOutDto wmsStockOutDto : list) {

                Map value = JSON.parseObject(JSON.toJSONString(wmsStockOutDto), Map.class);

                switch (wmsStockOutDto.getOutType().toString()){
                    case "0": value.put("outType","订单出货出库");
                        break;
                    case "1": value.put("outType","其它仓库调配出库");
                        break;
                    default:
                }
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                if (wmsStockOutDto.getOutboundTime()!=null) {

                    String s = simpleDateFormat.format(wmsStockOutDto.getOutboundTime());

                    value.put("outboundTime",s);

                }
                value.put("index",index++);

                map.add(value);
            }

            //创建HSSFWorkbook
            ExcelOutUtil excelExport = new ExcelOutUtil();
            excelExport.setFileName(fileName);
            excelExport.setData(map);
            excelExport.setHeardKey(properties);
            excelExport.setFontSize(14);
            excelExport.setSheetName(sheetName);
            excelExport.setTitle(sheetName);
            excelExport.setHeardList(title);
            String s = excelExport.exportExport(request, response, page, 2, mergePaperPath);

            tempPath.add(new File(s));

            if (list == null || list.size() < size){
                flag=false;
                break;
            }

            page++;
        }
        fileToZip(mergePaperPath,mergePaperPath,zipName);

        helpdown(request,response,mergePaperPath+zipNameString);

        //删除文件
        for (File temp : tempPath) {
            temp.delete();
        }
        //删除 压缩包
        new File(mergePaperPath+zipNameString).delete();
    }

    //入库统计
    @RequestMapping("/inCount")
    @ResponseBody
    public void export2(
            @ApiParam(name = "page", value = "分页值", defaultValue = "0") @RequestParam(defaultValue = "1") Integer page,
            @ApiParam(name = "size", value = "每分页返回的记录数", defaultValue = "0") @RequestParam(defaultValue = "1000") Integer size,
            @ApiParam(name = "warehouseId", value = "仓库id", defaultValue = "0") @RequestParam(required = false) Long warehouseId,
            @ApiParam(name = "specId", value = "产品id", defaultValue = "0") @RequestParam(required = false) Long specId,
            @ApiParam(name = "inType", value = "入库类型", defaultValue = "0") @RequestParam(required = false) Byte inType,
            @ApiParam(name = "beginTime", value = "开始时间", defaultValue = "0") @RequestParam(required = false) Long beginTime,
            @ApiParam(name = "endTime", value = "结束时间", defaultValue = "0") @RequestParam(required = false) Long endTime,
            @ApiParam(name = "minPrice", value = "低价", defaultValue = "0") @RequestParam(required = false) Integer minPrice,
            @ApiParam(name = "maxPrice", value = "高价", defaultValue = "0") @RequestParam(required = false) Integer maxPrice,
            @ApiParam(name = "maxPrice", value = "高价", defaultValue = "0") @RequestParam(required = false) Boolean isDelete,
            @ApiParam(name = "purchaseId", value = "单号", defaultValue = "0") @RequestParam(required = false) Long purchaseId,
            HttpServletRequest request, HttpServletResponse response
    ) throws Exception {

        //excel标题
        String[] title ={ "序号", "所属仓库", "商品名称","商品父类","商品分类", "入库类型", "入库数量","采购价格(分)","入库时间","生产日期",};

        String [] properties = new String[]{"index", "warehouseName", "specName","parentName","categoryName","inType", "inNumber", "supplyPrice","inboundTime","mfgDate"};
        //excel文件名
        String fileName = "入库统计" + System.currentTimeMillis() + ".xls";

        //sheet名
        String sheetName = "入库统计表";

        //zip文件名
        String zipName = "入库统计表";

        //zip路径名
        String zipNameString = zipName+".zip";

        //不同系统文件夹的生成
        String mergePaperPath = getMergePaperPath(new Date());


        //存入地址
        List<File> tempPath = new ArrayList<>();

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        boolean flag =true;

        while(flag){

            List<Map> map = new ArrayList<>();

            int index = 1;

            Wrapper<PageInfo<WmsStockInDto>> search = wmsStorageController.search1(page, size, warehouseId, specId, inType, beginTime, endTime,minPrice,maxPrice,isDelete,purchaseId);

            PageInfo<WmsStockInDto> result = search.getResult();

            List<WmsStockInDto> list = result.getList();

            for (WmsStockInDto wmsStockInDto : list) {

                Map value = JSON.parseObject(JSON.toJSONString(wmsStockInDto), Map.class);

                switch(wmsStockInDto.getInType().toString()){

                    case "0" :value.put("inType","采购入库");
                        break;
                    case "1" :value.put("inType","其他仓库调配入库");
                        break;
                    case "2" :value.put("inType","用户退货入库");
                        break;
                    default:
                }


                value.put("index",index++);
                if (wmsStockInDto.getInboundTime()!=null) {
                    value.put("inboundTime", simpleDateFormat.format(wmsStockInDto.getInboundTime()));
                }
                if (wmsStockInDto.getMfgDate()!=null) {
                    value.put("mfgDate", simpleDateFormat.format(wmsStockInDto.getMfgDate()));
                }
                map.add(value);
            }

            //创建HSSFWorkbook
            ExcelOutUtil excelExport = new ExcelOutUtil();
            excelExport.setFileName(fileName);
            excelExport.setData(map);
            excelExport.setHeardKey(properties);
            excelExport.setFontSize(14);
            excelExport.setSheetName(sheetName);
            excelExport.setTitle(sheetName);
            excelExport.setHeardList(title);
            String s = excelExport.exportExport(request, response, page, 2, mergePaperPath);

            tempPath.add(new File(s));

            if (list == null || list.size() < size){
                flag=false;
                break;
            }

            page++;
        }

        fileToZip(mergePaperPath,mergePaperPath,zipName);

        helpdown(request,response,mergePaperPath+zipNameString);

        //删除文件
        for (File temp : tempPath) {
            temp.delete();
        }
        //删除 压缩包
        new File(mergePaperPath+zipNameString).delete();

    }

    //库存管理
    @RequestMapping("/storageCount")
    @ResponseBody
    public void export(
            @ApiParam(name = "page", value = "分页值", defaultValue = "1") @RequestParam(defaultValue = "1") Integer page,
            @ApiParam(name = "size", value = "每分页返回的记录数", defaultValue = "1000") @RequestParam(defaultValue = "1000") Integer size,
            @ApiParam(name = "warehouseId", value = "仓库id", defaultValue = "0") @RequestParam(required = false) Long warehouseId,
            @ApiParam(name = "specId", value = "产品名称", defaultValue = "0") @RequestParam(required = false) Long specId,
            @ApiParam(name = "specName", value = "产品名称", defaultValue = "0") @RequestParam(required = false) String specName,
            @ApiParam(name = "categoryId", value = "商品分类id", defaultValue = "0") @RequestParam(required = false) Long categoryId,
            @ApiParam(name = "isEnable", value = "商品启用状态", defaultValue = "0") @RequestParam(required = false) Byte isEnable,
            @ApiParam(name = "beginNumber", value = "库存数量", defaultValue = "0") @RequestParam(required = false) Integer beginNumber,
            @ApiParam(name = "endNumber", value = "库存数量", defaultValue = "0") @RequestParam(required = false) Integer endNumber,
            @ApiParam(name = "qualityAlert", value = "保质期预警参数", defaultValue = "0") @RequestParam(required = false) Integer qualityAlert,
            @ApiParam(name = "stockinAlert", value = "入库天数预警", defaultValue = "0") @RequestParam(required = false) Integer stockinAlert,
            @ApiParam(name = "wareCategory", value = "仓库类别", defaultValue = "0") @RequestParam(required = false) Byte wareCategory,
            HttpServletRequest request,HttpServletResponse response
    ) throws Exception {

        //excel标题
        String[] title ={ "序号", "仓库名称", "商品名称","商品父类","商品分类", "库存数量", "市场价格(元)","批发价格(元)","启用状态","出厂天数(天)","在库天数(天)"};

        String [] properties = new String[]{"index", "warehouseName", "specName", "parentName","categoryName", "number", "marketPrice","stockPrice","isEnable","quantityDays","warehouseDays"};

        //excel文件名
        String fileName = "库存管理" + System.currentTimeMillis() + ".xls";

        //sheet名
        String sheetName = "库存管理表";

        //zip文件名
        String zipName = "库存管理表";

        //zip路径名
        String zipNameString = zipName+".zip";

        //不同系统文件夹的生成
        String mergePaperPath = getMergePaperPath(new Date());


        boolean flag =true;

        //存入地址
        List<File> tempPath = new ArrayList<>();

        while(flag){

            List<Map> map = new ArrayList<>();

            int index = 1;

            Wrapper<PageInfo<WmsStorage>> search = wmsStorageController.searchStorage(page, size, warehouseId, specId, specName,categoryId, isEnable,beginNumber, endNumber,qualityAlert,stockinAlert,wareCategory);

            PageInfo<WmsStorage> result = search.getResult();

            List<WmsStorage> list = result.getList();

            for ( WmsStorage wmsStorage : list) {

                wmsStorage.setMarketPrice(wmsStorage.getMarketPrice()/100);

                wmsStorage.setStockPrice(wmsStorage.getStockPrice()/100);

                wmsStorage.setNumber(wmsStorage.getNumber()-wmsStorage.getLockNumber());

                Map value = JSON.parseObject(JSON.toJSONString(wmsStorage), Map.class);

                switch (wmsStorage.getIsEnable().toString()){
                    case "false": value.put("isEnable","禁用");
                        break;
                    case "true": value.put("isEnable","启用");
                        break;
                    default:
                }

                value.put("index",index++);
                map.add(value);
            }

            //创建HSSFWorkbook
            ExcelOutUtil excelExport = new ExcelOutUtil();
            excelExport.setFileName(fileName);
            excelExport.setData(map);
            excelExport.setHeardKey(properties);
            excelExport.setFontSize(14);
            excelExport.setSheetName(sheetName);
            excelExport.setTitle(sheetName);
            excelExport.setHeardList(title);
            String s = excelExport.exportExport(request, response, page, 2, mergePaperPath);

            tempPath.add(new File(s));

            if (list == null || list.size() < size){
                flag=false;
                break;
            }
            page++;
        }

        fileToZip(mergePaperPath,mergePaperPath,zipName);

        helpdown(request,response,mergePaperPath+zipNameString);

        //删除文件
        for (File temp : tempPath) {
            temp.delete();
        }
        //删除 压缩包
        new File(mergePaperPath+zipNameString).delete();
    }


    //出库导出excel
    @RequestMapping("/purchaseReturn/export")
    @ResponseBody
    public void purchaseExport(@ApiParam(name = "page", value = "分页值", defaultValue = "0") @RequestParam(defaultValue = "1") Integer page,
                               @ApiParam(name = "size", value = "每分页返回的记录数", defaultValue = "0") @RequestParam(defaultValue = "1000") Integer size,
                               @ApiParam(name = "wmsPurchaseOrderDto", value = "参数") @RequestBody WmsPurchaseReturnOrderDto wmsPurchaseReturnOrderDto,
                               HttpServletRequest request,HttpServletResponse response) throws IOException {

        //excel标题
        String[] title ={ "序号","进货退货订单号", "支付类型","订单创建时间","经办人", "应付金额", "实付金额","供应商","支付账号","备注"};

        String [] properties = new String[]{"index", "purchaseReturnId", "payType","createTime","updateName","payable", "payment","supplierName","account","remark"};
        //excel文件名
        String fileName = "进货退货单" + System.currentTimeMillis() + ".xls";

        //sheet名
        String sheetName = "进货退货单";

        //zip文件名
        String zipName = "进货退货单";

        //zip路径名
        String zipNameString = zipName+".zip";

        //不同系统文件夹的生成
        String mergePaperPath = getMergePaperPath(new Date());

        //存入地址
        List<File> tempPath = new ArrayList<>();

        boolean flag =true;

        while(flag){

            List<Map> map = new ArrayList<>();

            PageHelper.startPage(page, size);

            List<WmsPurchaseReturnOrderDto> list = wmsPurchaseReturnOrderService.selectCondition(wmsPurchaseReturnOrderDto);

            PageInfo<WmsPurchaseReturnOrderDto> pageInfo = new PageInfo<>(list);

            List<WmsPurchaseReturnOrderDto> infoList = pageInfo.getList();

            int index = 1;

            for (WmsPurchaseReturnOrderDto orderGoodsDto : infoList) {

                Map value = JSON.parseObject(JSON.toJSONString(orderGoodsDto), Map.class);

                BigDecimal a = new BigDecimal((float)orderGoodsDto.getReceipts()/100);

                Double receipts  = a.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();

                BigDecimal b = new BigDecimal((float)orderGoodsDto.getReceivable()/100);

                Double receivable  = b.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();

                switch (orderGoodsDto.getPayType().toString()) {
                    case "0": value.put("payType","未确认");
                        break;
                    case "1": value.put("payType","支付宝");
                        break;
                    case "2": value.put("payType","微信");
                        break;
                    case "3": value.put("payType","银联");
                        break;
                    case "4": value.put("payType","现金");
                        break;

                    default :
                        value.put("payType","未确认");
                }
                value.put("index",index++);

                value.put("payable",receivable);

                value.put("payment",receipts);

                value.put("createTime", DateUtil.getStringDate(orderGoodsDto.getCreateTime()));

                map.add(value);
            }


            //创建HSSFWorkbook
            ExcelOutUtil excelExport = new ExcelOutUtil();
            excelExport.setFileName(fileName);
            excelExport.setData(map);
            excelExport.setHeardKey(properties);
            excelExport.setFontSize(14);
            excelExport.setSheetName(sheetName);
            excelExport.setTitle(sheetName);
            excelExport.setHeardList(title);
            String s = excelExport.exportExport(request, response, page, 2, mergePaperPath);

            tempPath.add(new File(s));

            if (list == null || list.size() < size){
                flag=false;
                break;
            }

            page++;
        }


        fileToZip(mergePaperPath,mergePaperPath,zipName);

        helpdown(request,response,mergePaperPath+zipNameString);

        //删除文件
        for (File temp : tempPath) {
            temp.delete();
        }
        //删除 压缩包
        new File(mergePaperPath+zipNameString).delete();
    }


    //库存管理
    @PostMapping("/storageCountMore")
    @ResponseBody
    public void storageCountMore(
            @ApiParam(name = "page", value = "分页值", defaultValue = "1") @RequestParam(defaultValue = "1") Integer page,
            @ApiParam(name = "size", value = "每分页返回的记录数", defaultValue = "1000") @RequestParam(defaultValue = "1000") Integer size,
            @ApiParam(name = "WmsStoragePicDto", value = "dto",defaultValue = "0") @RequestBody WmsStoragePicDto wmsStoragePicDto,
            HttpServletRequest request,HttpServletResponse response
    ) throws Exception {
        //excel标题
        String[] title = {"序号", "仓库名称", "商品名称", "商品分类", "库存数量","锁定数量","市场价格(元)","指导价格(元)","批发价格(元)","商品状态","进货价格", "出厂天数(天)", "在库天数(天)", "销售类型"};

        String[] properties = new String[]{"index", "warehouseName", "specName", "categoryName", "number","lockNumber",
                "marketPriceDouble","guidancePriceDouble","stockPriceDouble", "isEnable","supplyPriceDouble","quantityDays", "warehouseDays", "saleType"};

        //excel文件名
        String fileName = "库存管理" + System.currentTimeMillis() + ".xls";

        //sheet名
        String sheetName = "库存管理表";

        //zip文件名
        String zipName = "库存管理表";

        //zip路径名
        String zipNameString = zipName + ".zip";

        //不同系统文件夹的生成
        String mergePaperPath = getMergePaperPath(new Date());


        boolean flag = true;

        //存入地址
        List<File> tempPath = new ArrayList<>();

        while (flag) {

            List<Map> map = new ArrayList<>();

            int index = 1;

            Wrapper<PageInfo<WmsStorage>> search =
                    wmsStorageController.searchMore(page, size, wmsStoragePicDto);

            PageInfo<WmsStorage> result = search.getResult();

            List<WmsStorage> list = result.getList();

            for (WmsStorage wmsStorage : list) {

                wmsStorage.setNumber(wmsStorage.getNumber() -
                        wmsStorage.getLockNumber());

                Map value = JSON.parseObject(JSON.toJSONString(wmsStorage),
                        Map.class);

                BigDecimal marketPriceDouble = new BigDecimal((float)wmsStorage.getMarketPrice()/100);

                value.put("marketPriceDouble", marketPriceDouble);

                BigDecimal guidancePriceDouble = new BigDecimal((float)wmsStorage.getGuidancePrice()/100);

                value.put("guidancePriceDouble", guidancePriceDouble);

                BigDecimal stockPriceDouble = new BigDecimal((float)wmsStorage.getStockPrice()/100);

                value.put("stockPriceDouble", stockPriceDouble);

                BigDecimal supplyPriceDouble = new BigDecimal((float)wmsStorage.getSupplyPrice()/100);

                value.put("supplyPriceDouble", supplyPriceDouble);

                switch (wmsStorage.getIsEnable().toString()) {
                    case "false":
                        value.put("isEnable", "禁用");
                        break;
                    case "true":
                        value.put("isEnable", "启用");
                        break;
                    default:
                }
                switch (wmsStorage.getSaleType().toString()) {
                    case "1":
                        value.put("saleType", "零售");
                        break;
                    case "2":
                        value.put("saleType", "批发");
                        break;
                    case "3":
                        value.put("saleType", "批发+零售");
                        break;
                    default:
                }

                value.put("index", index++);

                map.add(value);
            }

            //创建HSSFWorkbook
            ExcelOutUtil excelExport = new ExcelOutUtil();
            excelExport.setFileName(fileName);
            excelExport.setData(map);
            excelExport.setHeardKey(properties);
            excelExport.setFontSize(14);
            excelExport.setSheetName(sheetName);
            excelExport.setTitle(sheetName);
            excelExport.setHeardList(title);
            String s = excelExport.exportExport(request, response, page, 2,
                    mergePaperPath);

            tempPath.add(new File(s));

            if (list == null || list.size() < size) {
                flag = false;
                break;
            }
            page++;
        }

        fileToZip(mergePaperPath, mergePaperPath, zipName);

        helpdown(request, response, mergePaperPath + zipNameString);

        //删除文件
        for (File temp : tempPath) {
            temp.delete();
        }
        //删除 压缩包
        new File(mergePaperPath + zipNameString).delete();
    }


    }

